package com.test.config;

import com.test.exception.CustomAuthenticationEntryPoint;
import com.test.oauth2.CustomClientDetailsService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableResourceServer
// 启用方法级权限控制
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

    @Getter
    @Setter
    private List<String> anonymousUrls = new ArrayList<>();

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //添加默认的url
        anonymousUrls.add("/favicon.ico");
        anonymousUrls.add("/error");
        anonymousUrls.add("/**/*NoLogin");
        anonymousUrls.add("/**/*Test");
        anonymousUrls.add("/oauth/token");
        anonymousUrls.add("/oauth/authorize");
        anonymousUrls.add("/oauth/logout");
        anonymousUrls.add("/oauth/checkToken");
        anonymousUrls.add("/oauth/randomCaptcha");
        anonymousUrls.add("/service/core/getNumberInfo");
        anonymousUrls.add("/service/core/delRedisDataByPreKeysAnon");
        anonymousUrls.add("/login");
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
        http
                .csrf().disable()
                .cors()
                .and()
                .exceptionHandling()
                // 定义的不存在access_token时候响应
                .authenticationEntryPoint(customAuthenticationEntryPoint)
                .and()
                .authorizeRequests()
                .antMatchers(anonymousUrls.toArray(new String[0])).permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }
}
